import easygui as eg
from database import Database


def show_tourist_management(db, current_user):
    while True:
        # 获取游客列表
        tourists = db.execute_query("""
            SELECT t.TouristID, u.RealName, t.IDNumber, 
                   t.Gender, t.Age, u.Phone,
                   CASE WHEN u.Status = 1 THEN '启用' ELSE '禁用' END AS StatusText
            FROM Tourists t
            JOIN Users u ON t.UserID = u.UserID
            ORDER BY u.RealName
        """)

        if not tourists:
            eg.msgbox("没有游客数据", "游客管理")
            break

        # 格式化显示
        tourist_list = [
            f"ID:{t['TouristID']} | 姓名:{t['RealName']} | 身份证:{t['IDNumber']} | "
            f"性别:{t['Gender'] or '无'} | 电话:{t['Phone'] or '无'}"
            for t in tourists
        ]

        # 添加操作选项
        tourist_list.extend(["", "=== 操作选项 ===", "1. 查看详情", "2. 报名确认", "3. 编辑信息", "4. 返回"])

        choice = eg.choicebox("游客管理系统", "游客管理", tourist_list)

        if not choice or choice == "4. 返回":
            break

        if choice == "1. 查看详情":
            tourist_id = get_id_from_choice(choice)
            if tourist_id:
                view_tourist_details(db, tourist_id)
        elif choice == "2. 报名确认":
            tourist_id = get_id_from_choice(choice)
            if tourist_id:
                confirm_registration(db, tourist_id)
        elif choice == "3. 编辑信息":
            tourist_id = get_id_from_choice(choice)
            if tourist_id:
                edit_tourist_info(db, tourist_id)


def get_id_from_choice(choice):
    if "ID:" not in choice:
        return None
    return int(choice.split("ID:")[1].split("|")[0].strip())


def view_tourist_details(db, tourist_id):
    # 获取游客详细信息
    tourist = db.execute_query("""
        SELECT t.*, u.Username, u.RealName, u.Email, u.Phone, u.Status
        FROM Tourists t
        JOIN Users u ON t.UserID = u.UserID
        WHERE t.TouristID = ?
    """, (tourist_id,))[0]

    # 获取参加的旅游团
    groups = db.execute_query("""
        SELECT tg.GroupID, tg.GroupName, tr.RouteName, 
               tg.StartDate, tg.EndDate, gm.Status, gm.PaymentStatus
        FROM GroupMembers gm
        JOIN TravelGroups tg ON gm.GroupID = tg.GroupID
        JOIN TravelRoutes tr ON tg.RouteID = tr.RouteID
        WHERE gm.TouristID = ?
    """, (tourist_id,))

    # 构建显示信息
    info = f"=== 基本信息 ===\n"
    info += f"用户名: {tourist['Username']}\n"
    info += f"真实姓名: {tourist['RealName']}\n"
    info += f"身份证号: {tourist['IDNumber']}\n"
    info += f"性别: {tourist['Gender'] or '无'}\n"
    info += f"年龄: {tourist['Age'] or '无'}\n"
    info += f"联系电话: {tourist['Phone'] or '无'}\n"
    info += f"电子邮箱: {tourist['Email'] or '无'}\n"
    info += f"状态: {'启用' if tourist['Status'] else '禁用'}\n"
    info += f"地址: {tourist['Address'] or '无'}\n"
    info += f"紧急联系人: {tourist['EmergencyContact'] or '无'}\n"
    info += f"紧急电话: {tourist['EmergencyPhone'] or '无'}\n\n"

    if groups:
        info += "=== 参加的旅游团 ===\n"
        for g in groups:
            info += (
                f"团ID: {g['GroupID']} | 团名: {g['GroupName']} | "
                f"线路: {g['RouteName']}\n"
                f"出发: {g['StartDate'].strftime('%Y-%m-%d')} | "
                f"结束: {g['EndDate'].strftime('%Y-%m-%d')} | "
                f"状态: {get_member_status(g['Status'])} | "
                f"支付: {'已支付' if g['PaymentStatus'] else '未支付'}\n\n"
            )
    else:
        info += "=== 暂无参加的旅游团 ===\n"

    eg.textbox("游客详细信息", "游客详情", info)


def get_member_status(status):
    status_map = {
        'pending': '待确认',
        'confirmed': '已确认',
        'cancelled': '已取消'
    }
    return status_map.get(status, status)


def confirm_registration(db, tourist_id):
    # 获取可报名的旅游团
    groups = db.execute_query("""
        SELECT tg.GroupID, tg.GroupName, tr.RouteName, 
               tg.StartDate, tg.EndDate, tg.MaxPeople, tg.CurrentPeople
        FROM TravelGroups tg
        JOIN TravelRoutes tr ON tg.RouteID = tr.RouteID
        WHERE tg.Status = 'confirmed'
        AND tg.GroupID NOT IN (
            SELECT GroupID FROM GroupMembers 
            WHERE TouristID = ? AND Status != 'cancelled'
        )
    """, (tourist_id,))

    if not groups:
        eg.msgbox("没有可报名的旅游团", "提示")
        return

    # 格式化显示
    group_list = [
        f"ID:{g['GroupID']} | 团名:{g['GroupName']} | 线路:{g['RouteName']} | "
        f"人数:{g['CurrentPeople']}/{g['MaxPeople']} | "
        f"时间:{g['StartDate'].strftime('%Y-%m-%d')}到{g['EndDate'].strftime('%Y-%m-%d')}"
        for g in groups
    ]

    choice = eg.choicebox("选择旅游团报名", "报名确认", group_list)

    if not choice:
        return

    group_id = get_id_from_choice(choice)

    # 确认报名
    if not eg.ynbox("确认报名这个旅游团吗？", "确认报名"):
        return

    try:
        # 检查是否已报名
        existing = db.execute_query("""
            SELECT 1 FROM GroupMembers 
            WHERE TouristID = ? AND GroupID = ?
        """, (tourist_id, group_id))

        if existing:
            # 更新状态
            db.execute_query("""
                UPDATE GroupMembers SET Status = 'confirmed'
                WHERE TouristID = ? AND GroupID = ?
            """, (tourist_id, group_id), False)
        else:
            # 新增报名
            db.execute_query("""
                INSERT INTO GroupMembers (TouristID, GroupID, Status)
                VALUES (?, ?, 'confirmed')
            """, (tourist_id, group_id), False)

        eg.msgbox("报名成功", "成功")
    except Exception as e:
        eg.msgbox(f"报名失败: {str(e)}", "错误")


def edit_tourist_info(db, tourist_id):
    # 获取当前信息
    tourist = db.execute_query("""
        SELECT t.*, u.RealName, u.Email, u.Phone, u.Status
        FROM Tourists t
        JOIN Users u ON t.UserID = u.UserID
        WHERE t.TouristID = ?
    """, (tourist_id,))[0]

    fields = [
        "身份证号*", "性别", "年龄",
        "联系电话", "电子邮箱", "地址",
        "紧急联系人", "紧急联系电话", "状态(1启用/0禁用)"
    ]
    values = [
        tourist['IDNumber'],
        tourist['Gender'] or "",
        str(tourist['Age']) if tourist['Age'] else "",
        tourist['Phone'] or "",
        tourist['Email'] or "",
        tourist['Address'] or "",
        tourist['EmergencyContact'] or "",
        tourist['EmergencyPhone'] or "",
        str(tourist['Status'])
    ]

    new_values = eg.multenterbox(f"编辑游客信息: {tourist['RealName']}", "游客编辑", fields, values)

    if not new_values:
        return

    # 验证必填字段
    if not new_values[0]:
        eg.msgbox("身份证号为必填项", "错误")
        return

    try:
        # 更新游客表
        db.execute_query("""
            UPDATE Tourists SET 
                IDNumber = ?, Gender = ?, Age = ?,
                Address = ?, EmergencyContact = ?, EmergencyPhone = ?
            WHERE TouristID = ?
        """, (*new_values[:3], new_values[5], new_values[6], new_values[7], tourist_id), False)

        # 更新用户表
        db.execute_query("""
            UPDATE Users SET 
                Email = ?, Phone = ?, Status = ?
            WHERE UserID = (SELECT UserID FROM Tourists WHERE TouristID = ?)
        """, (new_values[4], new_values[3], new_values[8], tourist_id), False)

        eg.msgbox("游客信息更新成功", "成功")
    except Exception as e:
        eg.msgbox(f"更新失败: {str(e)}", "错误")
